package frame.managermeau;

import frame.managermeau.add.AddProductFrame;
import frame.managermeau.add.AddInsuranceFrame;
import frame.managermeau.add.AddFundFrame;
import frame.model.SnowflakeIdWorker;
import sun.awt.image.codec.JPEGParam;

import javax.swing.*;
import javax.swing.table.*;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class ManagerHomepageFrame extends JFrame {
    private List<String> res;
    Connection con;
    SnowflakeIdWorker idWorker;
    public int[][] width=new int[][]{{100},{150,50,50,50,50,50},{150,50,50,50,50,50,50,50},{150,50,50,50,50}};
    public int index;
    public String[] names=null;
    private Object[][] object=null;
    DefaultTableModel tableModel=new DefaultTableModel(object,names);
    public void init() {
        try {
            Class.forName("org.opengauss.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            con = DriverManager.getConnection("jdbc:opengauss://121.36.41.207:26000/finance??useUnicode=true&characterEncoding=UTF-8", "geqiyu", "Tlyz0729");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            // 设置db1为搜索路径
            PreparedStatement firstStep = con.prepareStatement("SET SEARCH_PATH TO finance,public");
            firstStep.execute();
            firstStep.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        idWorker = new SnowflakeIdWorker(0, 0);
    }
    public ManagerHomepageFrame() {
        this.setTitle("管理员界面");
        //操作
        this.setContentPane(showOptions());
        //设置窗口
        this.setBounds(580,280,700,700);
//        this.setUndecorated(true);
//        this.setOpacity(0.90f);
        this.setLocationRelativeTo(null);
//        this.add(showOptions());

        this.setVisible(true);
        this.addWindowListener(new WindowListener() {
            @Override
            public void windowOpened(WindowEvent e) {

            }

            @Override
            public void windowClosing(WindowEvent e) {

            }

            @Override
            public void windowClosed(WindowEvent e) {
                try {
                    con.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }

            @Override
            public void windowIconified(WindowEvent e) {

            }

            @Override
            public void windowDeiconified(WindowEvent e) {

            }

            @Override
            public void windowActivated(WindowEvent e) {

            }

            @Override
            public void windowDeactivated(WindowEvent e) {

            }
        });

    }
    public String[] getTableName(int index){

        if(index==0){
            names=new String[]{"产品"};
//            width=new int[]{100};
        }
        else if(index==1){
//            width=new int[]{150,50,50,50,50,50};
            names=new String[]{"编号","名称","类型","风险等级","管理着","是否在售"};
        }
        if(index==2){
//            width=new int[]{150,50,50,50,50,50,50,50};
            names=new String[]{"编号","名称","最低年龄","最高年龄","价格","保险项目","保险期限","是否在售"};
        }
        else if(index==3){
//            width=new int[]{150,50,50,50,50};
            names=new String[]{"编号","名称","描述","投资期限","是否在售"};
        }
        return names;
    }

    public Object[][] getTableData(int index){


        if(index==0){
            object=new Object[5][8];
        }
        else if(index==1){
            try {
                PreparedStatement preparedStatement=con.prepareStatement("SELECT * FROM t_fund");
                ResultSet resultSet=preparedStatement.executeQuery();
                object=new Object[resultSet.getRow()==0?10:resultSet.getRow()+5][6];
                int row=0;
                while(resultSet.next()){
                    for(int coloum=1;coloum<=6;coloum++)
                        object[row][coloum-1]=resultSet.getObject(coloum);
                    row++;
                }
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(index==2){
            try {
                PreparedStatement preparedStatement=con.prepareStatement("SELECT * FROM  t_insurance");
                ResultSet resultSet=preparedStatement.executeQuery();
                object=new Object[resultSet.getRow()==0?10:resultSet.getRow()+5][8];
                int row=0;
                while(resultSet.next()){
                    for(int coloum=1;coloum<=8;coloum++)
                        object[row][coloum-1]=resultSet.getObject(coloum);
                    row++;
                }
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            } catch (SQLException e) {
                e.printStackTrace();
           }
//            finally {
//                try {
//                    con.close();
//                } catch (SQLException e) {
//                    e.printStackTrace();
//                }
//            }

        }
        if(index==3){
            try {
                PreparedStatement preparedStatement=con.prepareStatement("SELECT * FROM  t_product");
                ResultSet resultSet=preparedStatement.executeQuery();
                object=new Object[resultSet.getRow()==0?10:resultSet.getRow()+5][5];
                int row=0;
                while(resultSet.next()){
                    for(int coloum=1;coloum<=5;coloum++)
                        object[row][coloum-1]=resultSet.getObject(coloum);
                    row++;
                }
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    }
                 }  catch (SQLException e) {
                        e.printStackTrace();
                 }
//            finally {
//                    try {
//                        con.close();
//                    }   catch (SQLException e) {
//                        e.printStackTrace();
//                        }
//                }
        }
//        DefaultTableModel defaultTableModel=new DefaultTableModel(object,names);
//        JTable result=new JTable(defaultTableModel);
//        JScrollPane s=new JScrollPane(result);

        //滚动条
//        result.setPreferredScrollableViewportSize(new Dimension(50, 30));
//        result.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
//        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
//        renderer.setOpaque(false);
//        for(int i=0;i<names.length;i++){
//            result.getColumn(names[i]).setCellRenderer(renderer);//单格渲染
//            TableColumn column = result.getTableHeader().getColumnModel().getColumn(i);
//            column.setHeaderRenderer(renderer);//表头渲染
//        }
//        result.setOpaque(false);
//        result.getTableHeader().setOpaque(false);
//        result.getTableHeader().setBorder(BorderFactory.createBevelBorder(0));
//        s.getVerticalScrollBar().setOpaque(false);//滚动条设置透明
//        s.setOpaque(false);
//        s.getViewport().setOpaque(false);
//        s.setColumnHeaderView(result.getTableHeader());
//        s.getColumnHeader().setOpaque(false);
        return object;
    }

    private JPanel showOptions() {
        JPanel jPanel = new JPanel(null);

        //显示产品条目
        JComboBox product = new JComboBox();
        product.setSize(120,20);
        product.setLocation(30,20);
        product.addItem("产品");
        product.addItem("基金");
        product.addItem("保险");
        product.addItem("理财产品");
        jPanel.add(product);

        //增加产品按钮
        JButton addBtn = new JButton("增加");
        addBtn.setSize(60,40);
        addBtn.setLocation(200,20);
        jPanel.add(addBtn);

        //显示文本框
        JLabel jl = new JLabel("条目");
        jl.setSize(40, 20);
        jl.setLocation(480,200);
        jPanel.add(jl);
        JTextArea count = new JTextArea();
        count.setSize(60, 20);
        count.setLocation(520,200);
        jPanel.add(count);

        //上线产品按钮
        JButton upProduct = new JButton("上线");
        upProduct.setSize(60,40);
        upProduct.setLocation(500,300);
        jPanel.add(upProduct);

        //下线产品按钮
        JButton downProduct = new JButton("下线");
        downProduct.setSize(60,40);
        downProduct.setLocation(500,400);
        jPanel.add(downProduct);


//        结果框
//        JTextArea result = new JTextArea();
//        result.setSize(400, 500);
//        result.setLocation(30,100);
//        jPanel.add(result);
        tableModel=new DefaultTableModel(getTableData(0),getTableName(0));
        JTable jTable=new JTable();
        TableColumnModel cm = jTable.getColumnModel();
        jTable.setModel(tableModel);
        JScrollPane scrollPane = new JScrollPane(jTable);
        scrollPane.setBounds(10,150,450,500);
//        JTableHeader head = jTable.getTableHeader(); // 创建表格标题对象
//        head.setPreferredSize(new Dimension(head.getWidth(), 35));// 设置表头大小
//        head.setFont(new Font("楷体", Font.PLAIN, 18));// 设置表格字体
//        jTable.setRowHeight(18);// 设置表格行宽
        jTable.setLocation(10,150);
        jTable.setSize(450,500);
        TableColumn firsetColumn = jTable.getColumnModel().getColumn(0);
        firsetColumn.setPreferredWidth(150);
        firsetColumn.setMaxWidth(150);
        firsetColumn.setMinWidth(150);
//        for(int i=0;i<width.length;i++){
//            jTable.getColumnModel().getColumn(i).setPreferredWidth(width[i]);
//        }
//        jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//        jTable.setEnabled(false);
        jPanel.add(scrollPane);


        //显示产品条目
        product.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String pro = product.getSelectedItem().toString();
                if(pro.equals("基金"))index = 1;
                else if(pro.equals("保险")) index = 2;
                else if(pro.equals("理财产品")) index = 3;
//                result.setText("");
                if(!pro.equals("产品")) {
                    showMessage(pro);
                    for(int i=0;i<width.length;i++){
                        jTable.getColumnModel().getColumn(i).setPreferredWidth(width[index][i]);
                    }
                    jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//                    for(int i = 0; i < res.size(); i++) {
//                        result.append((new Integer(i)).toString() +  res.get(i) + "\n");
//                    }
                }
            }
        });

        //增加产品
        addBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String pro = product.getSelectedItem().toString();
                if(pro.equals("产品")) {
                    JOptionPane.showMessageDialog(null, "请选择！");
                }else {
                    if(pro.equals("基金")) {
                        new AddFundFrame().addWindowListener(new WindowListener() {
                            @Override
                            public void windowOpened(WindowEvent e) {

                            }

                            @Override
                            public void windowClosing(WindowEvent e) {
                                showMessage("基金");
                                for(int i=0;i<width.length;i++){
                                    jTable.getColumnModel().getColumn(i).setPreferredWidth(width[index][i]);
                                }
                                jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                            }

                            @Override
                            public void windowClosed(WindowEvent e) {
                                showMessage("基金");
                                for(int i=0;i<width.length;i++){
                                    jTable.getColumnModel().getColumn(i).setPreferredWidth(width[index][i]);
                                }
                                jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                            }

                            @Override
                            public void windowIconified(WindowEvent e) {

                            }

                            @Override
                            public void windowDeiconified(WindowEvent e) {

                            }

                            @Override
                            public void windowActivated(WindowEvent e) {

                            }

                            @Override
                            public void windowDeactivated(WindowEvent e) {

                            }
                        });
                    }

                    else if(pro.equals("保险")) {
                        new AddInsuranceFrame().addWindowListener(new WindowListener() {
                            @Override
                            public void windowOpened(WindowEvent e) {

                            }

                            @Override
                            public void windowClosing(WindowEvent e) {
                                showMessage("保险");
                                for(int i=0;i<width.length;i++){
                                    jTable.getColumnModel().getColumn(i).setPreferredWidth(width[index][i]);
                                }
                                jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                            }

                            @Override
                            public void windowClosed(WindowEvent e) {
                                showMessage("保险");
                                for(int i=0;i<width.length;i++){
                                    jTable.getColumnModel().getColumn(i).setPreferredWidth(width[index][i]);
                                }
                                jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                            }

                            @Override
                            public void windowIconified(WindowEvent e) {

                            }

                            @Override
                            public void windowDeiconified(WindowEvent e) {

                            }

                            @Override
                            public void windowActivated(WindowEvent e) {

                            }

                            @Override
                            public void windowDeactivated(WindowEvent e) {

                            }
                        });
                        showMessage("保险");
                    }else if(pro.equals("理财产品")) {
                        new AddProductFrame().addWindowListener(new WindowListener() {
                            @Override
                            public void windowOpened(WindowEvent e) {

                            }

                            @Override
                            public void windowClosing(WindowEvent e) {
                                showMessage("理财产品");
                                for(int i=0;i<width.length;i++){
                                    jTable.getColumnModel().getColumn(i).setPreferredWidth(width[index][i]);
                                }
                                jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                            }

                            @Override
                            public void windowClosed(WindowEvent e) {
                                showMessage("理财产品");
                                for(int i=0;i<width.length;i++){
                                    jTable.getColumnModel().getColumn(i).setPreferredWidth(width[index][i]);
                                }
                                jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                            }

                            @Override
                            public void windowIconified(WindowEvent e) {

                            }

                            @Override
                            public void windowDeiconified(WindowEvent e) {

                            }

                            @Override
                            public void windowActivated(WindowEvent e) {

                            }

                            @Override
                            public void windowDeactivated(WindowEvent e) {

                            }
                        });
                        showMessage("理财产品");
                    }
                }

            }
        });

        //上线产品
        upProduct.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(count.getText().length() == 0) {
                    JOptionPane.showMessageDialog(null, "请输入索引条目！");
                }else {
                    productOperate(index, 1,count.getText());
                    for(int i=0;i<width.length;i++){
                        jTable.getColumnModel().getColumn(i).setPreferredWidth(width[index][i]);
                    }
                    jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                }
            }
        });

        //下线产品
        downProduct.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(count.getText().length() == 0) {
                    JOptionPane.showMessageDialog(null, "请输入索引条目！");
                }else {
                    productOperate(index, 0,count.getText());
                    for(int i=0;i<width.length;i++){
                        jTable.getColumnModel().getColumn(i).setPreferredWidth(width[index][i]);
                    }
                    jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                }
            }
        });

        return jPanel;
    }

//    public void refresh(String pro){
//        init();
//        if(pro.equals("基金")){
//            object=getTableData(1);
//            names=getTableName(1);
//        }
//        else if(pro.equals("保险")){
//            object=getTableData(2);
//            names=getTableName(2);
//        }
//        else{
//            object=getTableData(3);
//            names=getTableName(3);
//        }
//
//        tableModel.setDataVector(object,names);
//        //        showTable(index);
////        List<String> res=showMessage(product);
////            for(int i = 0; i < res.size(); i++) {
////                result.append(  res.get(i) + "\n");
////            }
//        }

    /**
     * 返回产品的条目
     * @param product   产品名：基金、保险、理财产品
     * @return
     */
    private void showMessage(String product) {
//        List<String> result = new ArrayList<String>();
        /*
        -------------------------------------------------------------------------------------------------------------------------------
            业务逻辑
        -------------------------------------------------------------------------------------------------------------------------------
         */
        init();
//        ResultSet resultSet1=null;
//        ResultSet resultSet2=null;
//        ResultSet resultSet3=null;
        if(product.equals("基金")){
//                PreparedStatement preparedStatement1=con.prepareStatement("SELECT * FROM t_fund");
//                resultSet1=preparedStatement1.executeQuery();
//                result.clear();
//                result.add("基金：");
//                while(resultSet1.next()){
//                    result.add("    id:"+resultSet1.getString(1)+
//                            " name:"+resultSet1.getString(2)+
//                            " type:"+resultSet1.getString(3)+
//                            " risk:"+resultSet1.getInt(4)+
//                            " manager:"+resultSet1.getString(5)+
//                            " on_sale:"+resultSet1.getBoolean(6));
//                }
//                preparedStatement1.close();
//                resultSet1.close();
            names=getTableName(1);
            object=getTableData(1);

        }
        else if(product.equals("保险")){
//                PreparedStatement preparedStatement2=con.prepareStatement("SELECT * FROM t_insurance");
//                resultSet2=preparedStatement2.executeQuery();
//                result.clear();
//                result.add("保险：");
//                while(resultSet2.next()){
//                    result.add("    id:"+resultSet2.getString(1)+
//                            " name:"+resultSet2.getString(2)+
//                            " lowert age:"+resultSet2.getInt(3)+
//                            " largest age:"+resultSet2.getInt(4)+
//                            " price:"+resultSet2.getFloat(5)+
//                            " coverage:"+resultSet2.getString(6)+
//                            " period:"+resultSet2.getInt(7)+
//                            " on_sale:"+resultSet2.getBoolean((8)));
//                }
//                preparedStatement2.close();
            names=getTableName(2);
            object=getTableData(2);
//                resultSet2.close();
        }
        else{
//                PreparedStatement preparedStatement3=con.prepareStatement("SELECT * FROM t_product");
//                resultSet3=preparedStatement3.executeQuery();
//                result.clear();
//                result.add("理财产品：");
//                while(resultSet3.next()){
//                    result.add("    id:"+resultSet3.getString(1)+
//                            " name:"+resultSet3.getString(2)+
//                            " description:"+resultSet3.getString(3)+
//                            " period:"+resultSet3.getInt(4)+
//                            "on_sale:"+resultSet3.getBoolean(5));
//                }
//                preparedStatement3.close();
            names=getTableName(3);
            object=getTableData(3);
//                resultSet3.close();
        }
        tableModel.setDataVector(object,names);


//        for(int i=0;i<width.length;i++){
//            tableModel.getColumnModel().getColumn(i).setPreferredWidth(width[i]);
//        }

        //以下为测试代码
//        result.add("ddddd");

    }


    /**
     * 产品的上线与下线(有种特殊情况：产品以上线但是由于用户输入错误要求其上线)
     * @param flag      状态符，1表示上线，0表示下线
     * @param product   需要操作的产品条目
     * @param index  1基金,2保险，3理财产品
     */
    private void productOperate(int index,int flag, String product) {
        /*
        -------------------------------------------------------------------------------------------------------------------------------
            业务逻辑
        -------------------------------------------------------------------------------------------------------------------------------
         */
        PreparedStatement preparedStatement=null;
//        System.out.println(product+" "+index);
        try {
            if(index==1){
                preparedStatement=con.prepareStatement("SELECT * FROM t_fund WHERE fu_id =?", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                preparedStatement.setString(1,product);
                ResultSet resultSet=preparedStatement.executeQuery();
                if(resultSet.isBeforeFirst()==false){
                    JOptionPane.showMessageDialog(null, "不存在该记录");
                    return;
                }
                resultSet.next();
                if(flag==1)
                    resultSet.updateBoolean(6,true);
                else
                    resultSet.updateBoolean(6,false);
                resultSet.updateRow();
                showMessage("基金");
//                resultSet.close();
//                preparedStatement.execute();
            }
            else if(index==2){
                preparedStatement=con.prepareStatement("SELECT * FROM t_insurance WHERE in_id =?", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                preparedStatement.setString(1,product);
                ResultSet resultSet=preparedStatement.executeQuery();
                if(resultSet.isBeforeFirst()==false){
                    JOptionPane.showMessageDialog(null, "不存在该记录");
                    return;
                }
                resultSet.next();
//                System.out.println(resultSet.next());
//                System.out.println(resultSet.getString(1));
                if(flag==1)
                    resultSet.updateBoolean(8,true);
                else
                    resultSet.updateBoolean(8,false);
                resultSet.updateRow();
                showMessage("保险");
//                resultSet.close();
//                preparedStatement.execute();
            }
            else if(index==3){
                preparedStatement=con.prepareStatement("SELECT * FROM t_product WHERE fp_id =?", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                preparedStatement.setString(1,product);
                ResultSet resultSet=preparedStatement.executeQuery();
                if(resultSet.isBeforeFirst()==false){
                    JOptionPane.showMessageDialog(null, "不存在该记录");
                    return;
                }
                resultSet.next();
                if(flag==1)
                    resultSet.updateBoolean(5,true);
                else
                    resultSet.updateBoolean(5,false);
                resultSet.updateRow();
                showMessage("理财产品");
//                preparedStatement.execute();
//                resultSet.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        //返回操作结果情况
        String message = "您已经成功操作";
        JOptionPane.showMessageDialog(null, message);
//        String pro="";
//        if(index==1) pro+="基金";
//        else if(index==2) pro+="保险";
//        else pro+="理财产品";


    }




    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        new ManagerHomepageFrame();
    }
}
